package com.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import com.boot.bean.R;

import com.boot.service.RepliesService;
import com.boot.entity.Replies;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 回复表，存储用户的回复信息 前端控制器
 * </p>
 *
 * @author
 * @since 2025-02-09
 */
@RestController
@RequestMapping("/replies")
public class RepliesController {
    @Resource
    private RepliesService repliesService;
    @Autowired
    private UserService userService;

    //新增或者更新
    @PostMapping
    public R save(@RequestBody Replies replies, @RequestAttribute Integer userId) {
        replies.setUserId(userId);
        repliesService.saveOrUpdate(replies);
        return R.ok();
    }

    //删除
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id) {
        repliesService.removeById(id);
        return R.ok();
    }

    @PostMapping("/del/batch")
    public R deleteBatch(@RequestBody List<Integer> ids) {//批量删除
        repliesService.removeByIds(ids);
        return R.ok();
    }

    //查询所有数据
    @GetMapping
    public R findAll() {
        return R.ok(repliesService.list());
    }

    @GetMapping("/{id}")
    public R findOne(@PathVariable Integer id) {
        return R.ok(repliesService.getById(id));
    }

    @GetMapping("/page")
    public R findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, Integer discussionId) {
        QueryWrapper<Replies> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (discussionId != null) {
            queryWrapper.eq("discussion_id", discussionId);
        }
        IPage<Replies> page = repliesService.page(new Page<>(pageNum, pageSize), queryWrapper);
        for (Replies record : page.getRecords()) {
            record.setUser(userService.getById(record.getUserId()));
        }
        return R.ok(page);
    }
}

